package com.cb.filter;

import com.alibaba.fastjson.JSON;
import com.cb.utils.Result;
import com.cb.utils.WarehouseConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录限制的Servlet过滤器
 */
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    private StringRedisTemplate stringRedisTemplate;

    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        //获取请求url接口
        String url = request.getServletPath();
        System.out.println("---url----"+url);
        //白名单请求都直接放行
        String[] urlList=new String[]{
                "/captcha/captchaImage",
                "/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
                "/swagger-ui.html",
                "/product/img-upload"
        };
        boolean check = check(urlList, url);
        System.out.println(check);
        if(check){
            filterChain.doFilter(request,response);
            System.out.println("---自动放行----"+url);
            return;
        }

        //其它请求都校验token
        String clientToken = request.getHeader(WarehouseConstants.HEADER_TOKEN_NAME);
        //token校验通过,请求放行
        if(StringUtils.hasText(clientToken)&&stringRedisTemplate.hasKey(clientToken)){
            filterChain.doFilter(request,response);
            System.out.println("hello");
            return;
        }
        //token校验失败,向前端响应失败的Result对象转成的json串
        Result result = Result.err(Result.CODE_ERR_UNLOGINED, "尚未登录！");
        String jsonString = JSON.toJSONString(result);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(jsonString);
        out.flush();
        out.close();
    }

    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }

}
